//
//  BN_FaceChatViewController.m
//  BabyNow
//
//  Created by 刘泽琛 on 14-5-12.
//  Copyright (c) 2014年 iMobile. All rights reserved.
//

#import "BN_FaceChatViewController.h"
#import "UIBubbleTableView.h"
#import "UIBubbleTableViewDataSource.h"
#import "NSBubbleData.h"

@interface BN_FaceChatViewController () {
    BN_ChatHelper *chatHelper_;
    int KEYBORAD_HEIGHT;
    float inputBoxViewHeight;
}

@end

@implementation BN_FaceChatViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (IOS7) {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    self.tabBarController.tabBar.hidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"houtui"] style:UIBarButtonItemStylePlain target:self action:@selector(backRootVC)];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    UITapGestureRecognizer *keyBoardDownTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(keyBoardDownAction:)];
    [bubbleTableView addGestureRecognizer:keyBoardDownTap];
    
    switch (MAIN_VERSION) {
        case 6:
            bubbleTableView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-44-45);
            break;
        default:
            
            bubbleTableView.frame = CGRectMake(0, 0, SCREEN_WIDTH, FULLSCREEN_HEIGHT);
            bubbleTableView.contentInset = UIEdgeInsetsMake(64, 0, 45, 0);
            bubbleTableView.scrollIndicatorInsets = UIEdgeInsetsMake(64, 0, 45, 0);
            break;
    }

    self.userId = self.receiveDict[@"userId"];
    self.userName = self.receiveDict[@"userName"];
    self.title = [NSString stringWithFormat:@"%@",self.userName];

    if (!chatHelper_) {
        chatHelper_ = [[BN_ChatHelper alloc]init];
    }
    [self requestNet];
    // 输入框UIView
    self.inputBoxView = [[[NSBundle mainBundle]loadNibNamed:@"BN_PingLunInput" owner:nil options:nil]objectAtIndex:0];
    self.inputBoxView.inputBox.scrollEnabled = NO;
    self.inputBoxView.inputBox.delegate = self;
    self.inputBoxView.layer.shadowOffset = CGSizeMake(1, 0);
    self.inputBoxView.layer.shadowColor = [[UIColor grayColor] CGColor];
    self.inputBoxView.layer.shadowOpacity = 0.5;
    self.inputBoxView.layer.shadowRadius = 1;
    if (MAIN_VERSION >= 7) {
        self.inputBoxView.frame = CGRectMake(0, FULLSCREEN_HEIGHT-45, SCREEN_WIDTH, 45);
        inputBoxViewHeight = self.inputBoxView.frame.size.height;

    }else {
        self.inputBoxView.frame = CGRectMake(0, SCREEN_HEIGHT-45-44, SCREEN_WIDTH, 45);
        inputBoxViewHeight = self.inputBoxView.frame.size.height;
    }
    self.inputBoxView.inputBox.placeholder = @"说点什么吧...";
    [self.inputBoxView.sendBtn addTarget:self action:@selector(sendMessageAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.inputBoxView];
    
    // 注册改变inputboxView frame 的通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(inputBoxHeight:) name:KPOPKEYBOARDHEIGHT object:nil];
    // 风火轮
    [self viewLoadHintView];
}

#pragma mark
#pragma mark 响应事件
- (void)requestNet {
    __weak typeof(self) weakSelf = self;
    chatHelper_.queryChatDetailCompleteHandler = ^(id result,NSString *errMsg){
        // update by jason yan 2014-05-30
        if (errMsg) {
            [LZCHINT title:errMsg type:LZCError duration:2 places:HINT_PLACES callBack:NULL];
            [weakSelf cancelHintView];
        }
        if(result){
            [weakSelf bubbleList:result];
        }
    };
    [chatHelper_ refreshChatDetailListWithUserId:self.userId];
}

- (void)sendMessageAction {
    if (self.inputBoxView.inputBox.text.length<=0) {
        [SVProgressHUD showErrorWithStatus:@"请填写想说的内容"];
    }else {
        NSString *userId = self.userId;
        NSString *chatCont = self.inputBoxView.inputBox.text;
        __block BN_FaceChatViewController *blockSelf = self;
        [chatHelper_ sendChatContentWithUserId:userId chatContent:chatCont completeHandler:^(id result, NSString *errMsg) {
            if (errMsg) {
                blockSelf.inputBoxView.inputBox.text = @"";
                // 判断输入View回到原位置
                if (MAIN_VERSION >= 7) {
                    // 输入框
                    [blockSelf.inputBoxView.inputBox resignFirstResponder];
                    blockSelf.inputBoxView.frame = CGRectMake(0, FULLSCREEN_HEIGHT-45, SCREEN_WIDTH, 45);
                    blockSelf.inputBoxView.inputBox.frame = CGRectMake(9, 5, 245, 35);
                    inputBoxViewHeight = blockSelf.inputBoxView.frame.size.height;
                    // 列表
                    bubbleTableView.frame = CGRectMake(0, 0, SCREEN_WIDTH, FULLSCREEN_HEIGHT);
                    bubbleTableView.isReadSectionData = NO; // 数据控制保存row和section的单例
                    
                    // 请求数据
                    [blockSelf requestNet];
                    
                    /*[bubbleData addObject:[NSBubbleData dataWithText:chatCont andDate:[NSDate date] andType:BubbleTypeMine]];
                    [self bubbleList:bubbleData];
                    bubbleTableView.isReadSectionData = NO;
                    [bubbleTableView reloadData];
                    [weakSelf bubbleGetLastSection];*/
                }else {
                    // 输入框
                    [blockSelf.inputBoxView.inputBox resignFirstResponder];
                    blockSelf.inputBoxView.frame = CGRectMake(0, SCREEN_HEIGHT-45-44, SCREEN_WIDTH, 45);
                    blockSelf.inputBoxView.inputBox.frame = CGRectMake(9, 5, 245, 35);
                    inputBoxViewHeight = self.inputBoxView.frame.size.height;
                    
                    // 列表
                    bubbleTableView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-44-45);
                    bubbleTableView.isReadSectionData = NO; // 数据控制保存row和section的单例

                    // 请求数据
                    [blockSelf requestNet];
                    
                    
                    /*[bubbleData addObject:[NSBubbleData dataWithText:chatCont andDate:[NSDate date] andType:BubbleTypeMine]];
                    bubbleTableView.isReadSectionData = NO;
                    [bubbleTableView reloadData];
                    [weakSelf bubbleGetLastSection];*/
                }
            }else{
                // code...
            }
        }];
    }
}

// 键盘、输入框落下
- (void)keyBoardDownAction:(UITapGestureRecognizer *)tap {
    [self.inputBoxView.inputBox resignFirstResponder];
    [UIView animateWithDuration:0.3 animations:^{
        if (MAIN_VERSION >= 7) {
            self.view.frame = CGRectMake(0, 0, SCREEN_WIDTH, FULLSCREEN_HEIGHT);
            self.inputBoxView.frame = CGRectMake(0, FULLSCREEN_HEIGHT-inputBoxViewHeight, SCREEN_WIDTH, inputBoxViewHeight);
            bubbleTableView.frame = CGRectMake(0, 0, SCREEN_WIDTH, FULLSCREEN_HEIGHT);

        }else {
            self.inputBoxView.frame = CGRectMake(0, SCREEN_HEIGHT-inputBoxViewHeight-44, SCREEN_WIDTH, inputBoxViewHeight);
            bubbleTableView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-44-45);
        }
    } completion:^(BOOL finished) {
        // code...
    }];
}

- (void)inputBoxHeight:(NSNotification *)notification {
    
    [self bubbleGetLastSection];
    [UIView animateWithDuration:0.3 animations:^{
        KEYBORAD_HEIGHT = [notification.object intValue];
        self.inputBoxView.hidden = NO;
        if (MAIN_VERSION >= 7) {
            self.inputBoxView.frame = CGRectMake(0, FULLSCREEN_HEIGHT-inputBoxViewHeight-KEYBORAD_HEIGHT, SCREEN_WIDTH, inputBoxViewHeight);
            bubbleTableView.frame = CGRectMake(0, -(KEYBORAD_HEIGHT), SCREEN_WIDTH, FULLSCREEN_HEIGHT);
        }else {
            self.inputBoxView.frame = CGRectMake(0, SCREEN_HEIGHT-45-44-KEYBORAD_HEIGHT, SCREEN_WIDTH, 45);
            bubbleTableView.frame = CGRectMake(0, -(KEYBORAD_HEIGHT), SCREEN_WIDTH, SCREEN_HEIGHT-44-45);
        }
    } completion:^(BOOL finished) {
        // code...
    }];
}

- (void)bubbleList:(id)info {
    // 取消风火轮
    [self cancelHintView];
    NSDictionary *chatDict = (NSDictionary *)info
    ;
    NSArray *chatInfoArr = chatDict[@"chatInfo"];
    NSDictionary *userInfoDict = chatDict[@"userInfo"];
    NSString *mySelfUserId = [NSString stringWithFormat:@"%@",userInfoDict[@"userId"]];
    
    // 泡泡列表
    bubbleTableView.bubbleDataSource = self;
    bubbleData = [[NSMutableArray alloc]initWithCapacity:0];
    for (int i = 0; i < chatInfoArr.count; i++) {
        NSString *sendUserId = [NSString stringWithFormat:@"%@",chatInfoArr[i][@"sendUserId"]];
        NSString *timeStr = chatInfoArr[i][@"chatDate"];
        NSRange rang = NSMakeRange(0, 18);
        timeStr = [timeStr substringWithRange:rang];
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        NSTimeZone *timeZone = [NSTimeZone localTimeZone];
        [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        [formatter setTimeZone:timeZone];
        NSDate *dateTime = [formatter dateFromString:timeStr];
        
        NSString *contStr = chatInfoArr[i][@"cont"];
        
        if ([mySelfUserId isEqualToString:sendUserId]) {
            id chatInfo = [NSBubbleData dataWithText:contStr andDate:dateTime andType:BubbleTypeSomeoneElse];
            [bubbleData addObject:chatInfo];
        }else {
            id chatInfo = [NSBubbleData dataWithText:contStr andDate:dateTime andType:BubbleTypeMine];
            [bubbleData addObject:chatInfo];
        }
    }
    [bubbleTableView reloadData];
    [self bubbleGetLastSection];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

#pragma mark - UIBubbleTableViewDataSource implementation

- (NSInteger)rowsForBubbleTable:(UIBubbleTableView *)tableView
{
    return [bubbleData count];
}

- (NSBubbleData *)bubbleTableView:(UIBubbleTableView *)tableView dataForRow:(NSInteger)row
{
    return [bubbleData objectAtIndex:row];
}

- (void)bubbleGetLastSection {
    UIBubbleLastSectionData *sectionData = [UIBubbleLastSectionData sharedSectionData];
    NSLog(@"%ld,%ld",(long)sectionData.section,(long)sectionData.row);
    if ( sectionData.row == 0) {
        // code...
    }else {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:sectionData.row-1 inSection:sectionData.section];
        [bubbleTableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionNone animated:YES];
    }
}

#pragma mark
#pragma mark TextViewDelegate
- (void)textViewDidChange:(UITextView *)textView {
    UIFont * tfont = [UIFont systemFontOfSize:14];
    self.inputBoxView.inputBox.font = tfont;
    CGSize size =CGSizeMake(240,10000);
    NSDictionary * tdic = [NSDictionary dictionaryWithObjectsAndKeys:tfont,NSFontAttributeName,nil];
    
    switch (MAIN_VERSION) {
        case 7:
        {
            CGSize actualsize =[self.inputBoxView.inputBox.text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin |NSLineBreakByCharWrapping attributes:tdic context:nil].size;
            self.inputBoxView.inputBox.frame = CGRectMake(9, 5, 245, (actualsize.height-16.7019997)+35);
            self.inputBoxView.frame = CGRectMake(0, FULLSCREEN_HEIGHT-45-KEYBORAD_HEIGHT-(actualsize.height-16.7019997), SCREEN_WIDTH, 45+(actualsize.height-16.7019997));
            inputBoxViewHeight = self.inputBoxView.frame.size.height;
        }
            break;
        case 6:
        {
            CGSize iOS6size = [self.inputBoxView.inputBox.text  sizeWithFont:[UIFont systemFontOfSize:14.0f] constrainedToSize:size lineBreakMode:NSLineBreakByWordWrapping];
            if (iOS6size.height != 0) {
                self.inputBoxView.inputBox.frame = CGRectMake(9, 5, 245, (iOS6size.height-18)+35);
                self.inputBoxView.frame = CGRectMake(0, SCREEN_HEIGHT-inputBoxViewHeight-HEIGHT_NAV_BAR-KEYBORAD_HEIGHT, SCREEN_WIDTH, 45+(iOS6size.height-18));
            }else {
                self.inputBoxView.inputBox.frame = CGRectMake(9, 5, 245, 35);
                self.inputBoxView.frame = CGRectMake(0, SCREEN_HEIGHT-inputBoxViewHeight-HEIGHT_NAV_BAR-KEYBORAD_HEIGHT, SCREEN_WIDTH, 45);
            }
            inputBoxViewHeight = self.inputBoxView.frame.size.height;
        }
            break;
        default:
            break;
    }
}

#pragma mark 
#pragma mark 生命周期
- (void)backRootVC {
    [self releaseResource];
    [[NSNotificationCenter defaultCenter]postNotificationName:KREFRESH_CHATHOSTLIST object:nil];
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void)releaseResource {
    [[NSNotificationCenter defaultCenter]removeObserver:self name:KREFRESH_CHATHOSTLIST object:nil];
    bubbleTableView.delegate = nil;
    bubbleTableView.dataSource = nil;
    bubbleTableView = nil;
    
    bubbleData = nil;
    self.inputBoxView.inputBox.delegate = nil;
    self.inputBoxView.inputBox = nil;
    self.inputBoxView = nil;
    
    UIBubbleLastSectionData *sectionData = [UIBubbleLastSectionData sharedSectionData];
    sectionData.row = 0;
    sectionData.section = 0;
    sectionData = nil;
    
    [chatHelper_ cancelQueryChatDetailList];
    chatHelper_ = nil;
}

- (void)dealloc
{
    [self releaseResource];
    NSLog(@"聊聊会话详情 dealloc...");
}
@end
